package com.shimmer.beenFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Package com.shimmer.simpleFactory
 * @Author shimmer
 * @Date 2020/8/10 14:17
 * @TODO
 */

/*
 * 对象创建的两种方法：
 *   1.直接调用构造方法 UserService userService = new UserServiceImpl();
 *   2.通过反射创建对象
 *       Class clazz = Class.forName("类权限名")
 *       UserService userService = (userService) clazz.newInstance();
 * */
public class BeenFactory {
    private static Properties properties = new Properties();

    static {
        try {
            // 第一步 获取IO流
            InputStream inputStream = BeenFactory.class.getResourceAsStream("/applicationContext.properties");
            // 第二步 加载到properties集合
            properties.load(inputStream);
            // 第三步关闭流
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static UserService getBeen() {
        UserService userService = null;
        try {
            Class clazz = Class.forName(properties.getProperty("userService"));
            userService = (UserService) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return userService;
    }
    
    public static UserService getNewBeen(){
        UserService userService = null;
        try {
            Class clazz = Class.forName(properties.getProperty("userServiceNew"));
            userService = (UserService) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return userService;
    }
    
    // 通用的工厂方法
    public static Object getBeen(String been){
        Object obj = null;
        try {
            Class clazz = Class.forName(properties.getProperty(been));
            obj = clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }

}
